<template>
  <view>
    <xmInfo
      :projectno="itemContent.projectno"
      :projectname="itemContent.projectname"
      ref="xmInfo"
    ></xmInfo>
    <scroll-view
      class="scroll-list"
      scroll-y="true"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      @scrolltoupper="refresherrefresh"
      :style="{ height: computedScrollViewHeight }"
    >
    <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight }"
      >
        <!-- @click="add(item)" -->
        <view
          class="cu-item shadow"
          v-for="(item, index) in list"
          :key="item.id"
        >
          <view
            class="cu-form-group"
            style="display: flex; justify-content: space-between"
          >
            <view
              style="
                display: inline-block;
                padding: 5px;
                background: #3e97b0;
                color: #fff;
                width: 40px;
                text-align: center;
                font-style: italic;
                font-weight: bold;
              "
            >
              {{ index + 1 }}
            </view>
            <dictLabel
              :value="item.status ? item.status : 0"
              dict-type="bpm_biz_status"
              :dict-list="dictList"
              :fontSize="'30rpx'"
            ></dictLabel>
          </view>
          <view class="cu-form-group">
            <view class="text-xl text-bold">申请时间</view>
            <view class="text-xl text-bold">{{ formatDate(item.createDate) }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">工程编码</view>
            <view>{{ item.projectno }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">工程名称</view>
            <view>{{ item.projectname }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">申请人</view>
            <view>{{ item.createByName }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">停水时间</view>
            <view>{{ formatDate(item.connectwatertime)}}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">接水完成时间</view>
            <view>{{ formatDate(item.sponsordate) }}</view>
          </view>
          <view
            class="cu-form-group"
            style="color: #3e97b0"
          >
			<view class="content-footer-right">
				<view v-if="item.status == '4' || item.status == '5' || item.status == '6'" @click="handleBpmMyTask({id:item.id})"><u-icon name="checkmark-circle"></u-icon>任务办理</view>
			</view>
			<view @click="add(item)">
				查看详情<u-icon name="arrow-right"></u-icon>
			</view>
			
			
          </view>
          <!-- <view class="dictLabel">
				  <dictLabel
				    :value="item.status ? item.status : 0"
				    dict-type="bpm_biz_status"
				    :dict-list="dictList"
				    :fontSize="'30rpx'"
				  ></dictLabel>
				</view> -->
        </view>
        <view v-if="list.length" class="loadmore">
            <u-loadmore :status="loadStatus"></u-loadmore>
        </view>
        <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
      </view>

    </scroll-view>
    <view class="btn-group cu-bar foot" v-if="addflag">
      <button :disabled="projStatus=='5' || projStatus=='6' || projStatus=='7'?true:false" class="cu-btn bg-green shadow-blur" @click="add('')">
        <text class="cuIcon-add"></text>发起接水
      </button>
    </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo, dictLabel },
  data() {
    return {
      triggered: false,
      loadStatus: "loadmore",
      query: {
        pageNo: 1,
        pageSize: 20,
      },
      itemContent: {},
      list: [],
      modalNameDetail: null,
      applyFile: [],
      showAddDetail: false,
      dictList: [],
      scrollViewHeight: 0,
      headerHeight: 0,
      addflag : hasPermission('app:btn:add:jieshuizuoye'),
      projStatus:this.$store.state.auth.projStatus,
    };
  },
  onShow() {
    this.query.pageNo = 1;
    this.loadList();
  },
  onLoad(e) {
    this.getDictList();
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        console.log(this.itemContent);
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === "auto"
        ? "auto"
        : `${this.scrollViewHeight}px`;
    },
  },

  methods: {
	  handleBpmMyTask(record){
	  	this.$u.api.bpm.bpmTaskDeForm({ formKey: 'Flow_ConnectWaterJob', bizKey: record.id }).then((res) => {
	  	  if(res.result == 'true'){
	  		  const url = res.mobileUrl;
          console.log(url, "url");
	  		  if (url && url != '') {
	  		  	uni.navigateTo({
	  		  		url: url
	  		  	})
	  		  }
	  	  }else{
	  		this.$u.toast(res.message);
	  	  }
	  	});
	  },
    async calculateScrollViewHeight() {
      try {
    // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height;
              resolve();
            });
          });
          // 计算tabBar高度
          // this.tabBarHeight = 100; // 假设tabbar高度为50px，实际应根据实际情况获取
		   if(this.addflag){
		   		  	this.tabBarHeight = 100; // 假设tabbar高度为50px，实际应根据实际情况获取
		   	}else{
		   		  	this.tabBarHeight = 0;
		   	}

          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;

          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }
    },
	getDictList() {
	  this.$u.api.dictListData({ dictType: "bpm_biz_status" }).then((res) => {
	    this.dictList = res;
	  });
	},
    formatDate(date) {
		if (!date) return '';
        const dateObj = new Date(date);
        const year = dateObj.getFullYear();
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        const h = dateObj.getHours();
        const m = dateObj.getMinutes();
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`;
    },
    add(item) {
      if (item) {
        uni.navigateTo({
          url:
            "/pages/zfgs/process/job/pmConnectwaterjob/form?id=" +
            item.id,
        });
      } else {
        uni.navigateTo({
          url:
            "/pages/zfgs/process/job/pmConnectwaterjob/createForm?projectno=" +
            this.itemContent.projectno +
            "&projectname=" +
            this.itemContent.projectname,
        });
      }
    },
    async openDocument(attachment) {
      // 在App端使用uni-app原生API
      if (process.env.UNI_PLATFORM === "app-plus") {
        const filePath = await this.downloadAndSaveAttachment(attachment.url);
        console.log("filePath", filePath);
        uni.openDocument({
          filePath: filePath,
          fileType: attachment.type,
          success: () => {},
          fail: () => {},
        });
      } else {
        // 在Web或小程序中，可能需要提供下载链接
        window.location.href = attachment.url;
      }
    },
    async downloadAndSaveAttachment(url) {
      // 这里是一个简化的下载并保存到本地临时文件的逻辑，实际开发中需要更完整的处理流程
      const { tempFilePath } = await uni.downloadFile({ url });
      return tempFilePath;
    },
    addDetail(applyFile) {
      this.showAddDetail = true;
      this.modalNameDetail = "bottomModal";
      this.applyFile = applyFile;
      console.log(applyFile, "applyFile", this.applyFile);
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
      this.showAddDetail = false;
    },
    async refresherrefresh() {
      console.log(22222);
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadList();
      this.triggered = false;
    },
    loadList(type) {
      this.$u.api.zfgs.pmConnectwaterjobListData(this.query).then((res) => {
        if (res.list.length < 20 || res.list.length == 0) {
          this.loadStatus = "nomore";
        }
        var list = res.list;
        if (type == "add") {
          for (var i = 0; i < list.length; i++) {
            this.list.push(list[i]);
          }
        } else {
          this.list = list;
        }
      });
    },
    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadList("add");
      }, 100);
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  }
};
</script>
<style lang="scss" scoped>
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
  min-height: 80px;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
  position: relative;
  overflow: visible;
}
.title {
  flex-shrink: 0;
}
.grid-square {
  margin-bottom: 0 !important;
}
.cuIcon-image {
  width: 40px;
  height: 40px;
}
.dictLabel {
  position: absolute;
  top: -10px;
  right: -10px;
}
</style>